package com.gitee.ice1938.module.admin.filemanager.fun;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jackrabbit.JcrConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.gitee.ice1938.admin.framwork.annotation.ReqOperation;
import com.gitee.ice1938.module.admin.filemanager.util.DownloadUtils;
import com.gitee.ice1938.mvc.base.LableValue;

@Controller
@RequestMapping("/repository")
public class WebdavControler {
	@Autowired
	private FileManageSvc fileManageSvc;

	@RequestMapping(path = { "", "/{workspace}", "/{workspace}/**" }, method = RequestMethod.GET)
	@ReqOperation
	public ModelAndView index(@PathVariable(value = "workspace", required = false) String workspace,
	        HttpServletRequest request, HttpServletResponse response, Model model) throws RepositoryException,
	        UnsupportedEncodingException {
		if (workspace == null) {
			workspace = "default";
		}
		String uri = java.net.URLDecoder.decode(request.getRequestURI(), "utf-8");
		String path = null;
		String pathP = "/repository/" + workspace;
		if (uri.indexOf(workspace) > 0 && !uri.endsWith(workspace)) {
			path = uri.split(workspace)[1].substring(1);
			if (path.isEmpty()) {
				path = null;
			} else if (path.indexOf("/") > 0) {
				pathP = path.substring(0, path.lastIndexOf("/"));
			}
		}

		List<FileNode> nodes = fileManageSvc.list(workspace, path);
		List<LableValue> data = new ArrayList<LableValue>();
		for (FileNode i : nodes) {
			if (i.getNtType().equals(JcrConstants.NT_FILE)) {
				DownloadUtils.download(i, request, response);
				return null;
			}
			data.add(new LableValue(i.getNodeName(), "/repository/" + workspace + i.getNodeName()));
		}
		model.addAttribute("workspace", workspace);
		model.addAttribute("path", path);
		model.addAttribute("pathP", pathP);
		model.addAttribute("pathP_href", "/repository/" + workspace + "/" + pathP);
		model.addAttribute("nodes", data);
		return new ModelAndView("module/admin/file_manage/view_browse", model.asMap());
	}
}
